#!/usr/bin/env ruby

require File.join(File.dirname(__FILE__), *%w".. lib tcl")

class ConsoleInterp < Tcl::Interp
  def initialize
    super
    expose :ruby_eval
    expose :exit
  end
  
  def tcl_ruby_eval(script)
    Kernel.eval(script)
  end
  
  def tcl_exit(code = 0)
    exit(code.to_i)
  end
end

filename = ARGV.shift || File.join(File.dirname(__FILE__), *%w".. .state.dat")
interp   = ConsoleInterp.load_from_file(filename) rescue ConsoleInterp.new
script   = ""

at_exit do
  File.open(filename, "w") do |file|
    file.write(interp.to_tcl)
  end
end

print ">> "
$stdin.each_line do |line|
  script << line
  if interp.list_to_array(script)
    begin
      result = interp.eval(script)
      puts result unless result.length.zero?
    rescue Tcl::Error => e
      puts "error: #{e}"
    end
    script = ""
    print ">> "
  else
    print "?> "
  end
end
